package com.sakila.dao;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sakila.dbo.CategoryDBO;
import com.sakila.util.DBConnection;

public class CategoryDAO implements ICategoryDAO {


	private Logger logger = Logger.getLogger(this.getClass());
	//SimpleDateFormat formatter = new SimpleDateFormat(
		//	"yyyy.MM.dd G 'at' HH:mm:ss z");

	/* (non-Javadoc)
	 * @see com.sakila.dao.ICategoryDAO#findById(int)
	 */
	@Override
	public CategoryDBO findById(int categoryId) {
		CategoryDBO dbo = null;
		ResultSet rs = null;
		PreparedStatement statement = null;
		Connection connection = null;
		try {
			connection = DBConnection.getConnection();
			StringBuilder sb = new StringBuilder();
			sb.append("select category_id as categoryId, name as name,last_update as lastUpdate");
			sb.append("from category ");
			sb.append("where category_id = " + categoryId);
			statement = connection.prepareStatement(sb.toString());
			logger.info("Executing Query Here in Actor DAO: "+ sb.toString());
			rs = statement.executeQuery();
			if (rs.next()) {
				dbo = new CategoryDBO();
				dbo.setCategory_id(rs.getInt("categoryId"));
				dbo.setName(rs.getString("name"));
				dbo.setLast_update(rs.getDate("lastUpdate"));
				
				
			}

		} catch (SQLException e) {
			logger.error("Exception in CategoryDAO" + e );
			throw new RuntimeException(e);
		} finally {
			DBConnection.close(rs, statement, connection);
		}
		return dbo;
	}

	/* (non-Javadoc)
	 * @see com.sakila.dao.ICategoryDAO#findAll()
	 */
	@Override
	public List<CategoryDBO> findAll() {
		List<CategoryDBO> returnList = null;
		ResultSet rs = null;
		PreparedStatement statement = null;
		Connection connection = null;
		CategoryDBO dbo = null;
		try {
			connection = DBConnection.getConnection();
			StringBuilder sb = new StringBuilder();
			sb.append("select category_id as categoryId, name as name,last_update as lastUpdate");
			sb.append("from category ");
			statement = connection.prepareStatement(sb.toString());
			logger.info("Executing Query Here Category DAO infindAll: "+ sb.toString());
			rs = statement.executeQuery();
			returnList = new ArrayList<CategoryDBO>();
			while (rs.next()) {
				dbo = new CategoryDBO();
				dbo = new CategoryDBO();
				dbo.setCategory_id(rs.getInt("categoryId"));
				dbo.setName(rs.getString("name"));
				dbo.setLast_update(rs.getDate("lastUpdate"));
				returnList.add(dbo);
				
			}

		} catch (SQLException e) {
			logger.error("Exception in Category DAO" + e );
			throw new RuntimeException(e);
		} finally {
			DBConnection.close(rs, statement, connection);
		}
logger.debug("Display Me everyone from List:" + returnList);
		return returnList;
	}
	
}

